import { createRouter, RouteRecordRaw, createWebHashHistory } from 'vue-router';
import {getAsideData} from "../service/aside/aside"
import {MenuItem} from "../viewModel/aside"
import {pinia} from "../main"
import {useRouterTabStore} from "../store/routerTab/routerTab"
const routerContext = require.context('./modules', true, /\.ts$/) // 获取路由模块的上下文


// 自动引入路由模块
let autoRoute: RouteRecordRaw[] = []
routerContext.keys().forEach(route => {
  const routerModule = routerContext(route) // 得到路由的模块
  // 兼容 import export 和 require module.export 两种规范
  autoRoute = [...autoRoute, ...(routerModule.default || routerModule)]
});
document.title = "saas-web"
const routes = [
  ...autoRoute,
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/:pathMatch(.*)",
    component: () => import("../pages/notFound/notFound.vue")
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      index: 1,
      title: '登录'
    },
    component: () => import('@/pages/login/loginPage.vue')
  },
  {
    path: '/register',
    name: 'register',
    meta: {
      index: 2,
      title: '注册'
    },
    component: () => import('@/pages/register/registerPage.vue')
  },

];
// 创建router实例
const router = createRouter({
  // history: createWebHistory(),
  history: createWebHashHistory(),
  routes,
})



export type RouteConfigs = RouteRecordRaw[];
function flattenMenuItems(menuData: MenuItem[],parentPath: string = ""): MenuItem[] {
  let result: MenuItem[] = [];
  let curfilePath:string = ""
  menuData.forEach((menuItem) => {
    let currentPath = parentPath? `${parentPath}/${menuItem.name}` : menuItem.name;
    menuItem.filePath = currentPath;
      if (menuItem.children && menuItem.children.length > 0) {
          // 递归调用处理子菜单
          curfilePath = `${curfilePath}${menuItem.name}`
          const childrenItems = flattenMenuItems(menuItem.children,currentPath);
          result = [...result,...childrenItems]
      } else {
        result.push(menuItem);
      }
  });
  return result;
}
// 模拟从后端获取动态路由数据的函数
export async function fetchDynamicRoutes(): Promise<RouteConfigs> {
  // 这里应该是实际的 API 调用，返回符合 RouteRecordRaw 结构的数组
 let fetchDynamiRoutes:MenuItem[] = await getAsideData()
let dynamicRoute:RouteConfigs = []
dynamicRoute = flattenMenuItems(fetchDynamiRoutes).map((item) => {
return {
  name:item.name,
  path: item.path,
  component: () => import(`@/pages/${item.filePath}.vue`)
}
})

  return dynamicRoute;
}
// 动态添加路由的函数
export async function addDynamicRoutes() {
  const dynamicRoutes = await fetchDynamicRoutes();
  const baseLayoutRouteIndex = router.getRoutes().findIndex((route) => route.name === 'baseLayout');
  if (baseLayoutRouteIndex > -1) {
    const baseLayoutRoute = router.getRoutes()[baseLayoutRouteIndex];
        const updatedBaseLayoutRoute = {...baseLayoutRoute, children: [...baseLayoutRoute.children,...dynamicRoutes] };
        router.addRoute(updatedBaseLayoutRoute);
        localStorage.setItem('dynamicRoutes', JSON.stringify(dynamicRoutes));
  }
}


// 添加路由守卫
router.beforeEach((to, from, next) => {
  const routeTabStore = useRouterTabStore(pinia)
  const isLoggedIn = localStorage.getItem("isLoggedIn")
  // const storedDynamicRoutes = localStorage.getItem('dynamicRoutes');
  // console.log("storedDynamicRoutes =》",storedDynamicRoutes);
  // console.log("to =>",to);
 if (to.meta.requiresAuth && !isLoggedIn) {
    // 如果要访问的路由需要认证，且用户未登录，则重定向到登录页面
    next('/login');
  } else {
    // 否则允许访问

    if (to.meta.showTab) {
      routeTabStore.setCurrentIndex(to.name as string)
      
      routeTabStore.addRouteTabsList(
        { name:to.name as string,title: to.meta.title as string,path:to.path as string}
      )
    }
    next()
  }
})
export default router